package file;

import java.io.File;
import java.io.FileInputStream;

import operator.Handler;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.xwpf.extractor.XWPFWordExtractor;
import org.apache.poi.xwpf.usermodel.XWPFDocument;

import pri.file.FOperator;
import common.Constant;
import common.Singleton;
import view.Main;

/**
 *
 * @author 柴家琪 Operations of Doc
 *
 */
public class DocOperator {
    private Main main;

    private static DocOperator docOperator;
    private DocOperator() {}
    public static DocOperator getOperator() {
        if(docOperator == null) {
            docOperator = new DocOperator();
            docOperator.main = Singleton.main();
        }
        return docOperator;
    }

    // 获取新的文件
    public void readDoc() {
        Handler handler = Singleton.handler();

        File selectedDoc;
        Constant.usingDoc = selectedDoc = Singleton.fUtil().findFile("docx", "doc");
        Constant.usingXDoc = null;
        main.initialData();

        if (selectedDoc == null)
            return;

        String source;
        if (FOperator.compare(selectedDoc, "doc"))
            source = this.sOfDoc(selectedDoc);
        else
            source = this.sOfDocx(selectedDoc);
        handler.setSource(source);
        handler.addNew();
        Singleton.fUtil().writeSourceText();// 写源文件
    }

    /**
     * 添加新的Docx文件
     */
    private String sOfDocx(File file) {
        String str = "";
        try {
            FileInputStream fis = new FileInputStream(file);
            XWPFDocument xdoc = new XWPFDocument(fis);
            XWPFWordExtractor extractor = new XWPFWordExtractor(xdoc);
            str = extractor.getText();
            extractor.close();
            fis.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        //

        return str;
    }

    /**
     * 添加新的Doc文件
     */
    private String sOfDoc(File file) {
        String str = "";
        try {
            FileInputStream fis = new FileInputStream(file);
            HWPFDocument doc = new HWPFDocument(fis);
            str = doc.getDocumentText();
            doc.close();
            fis.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return str;
    }
}
